package com.winit.deploy.task.tomcatTask;

import com.winit.common.util.ConfigUtil;
import com.winit.common.util.RedisUtil;
import com.winit.core.server.base.CmdOutputHandler;
import com.winit.core.task.*;
import com.winit.deploy.bean.WinitTomcatInfo;
import com.winit.deploy.server.WinitTomcatServer;
import com.winit.project.util.ProjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by wangjian on 16/8/10.
 * 发布任务step5 启动server
 */
public class DeployStartServerTask extends Task {

    static final Logger logger = LoggerFactory.getLogger(DeployStartServerTask.class);

    private WinitTomcatServer winitTomcatServer;
    private boolean isCleanRedis = false;

    public DeployStartServerTask(String taskId, Integer expireTime, boolean isCleanRedis, WinitTomcatServer winitTomcatServer) {
        super(taskId, expireTime);
        this.winitTomcatServer = winitTomcatServer;
        this.isCleanRedis = isCleanRedis;
    }

    @Override
    public TaskStatus call() throws Exception {
        logger.info("com.winit.deploy.task.tomcatTask.DeployStartServerTask.call start taskId=" + this.taskId);
        final StringBuffer str = new StringBuffer();
        CmdOutputHandler handler = new CmdOutputHandler() {

            @Override
            public void onMessage(String cmd, int index, String message, Boolean isErrorMessage) {
                str.append(message);
            }
        };
        this.winitTomcatServer.doStartServer(handler);
        logger.info("DeployStartServerTask:返回," + str.toString());
        if (!(str.toString()).startsWith("Start Tomcat complete ok") &&
                !(str.toString()).startsWith("tomcat service is running")) {
            throw new Exception(str.toString());
        }
        logger.info("com.winit.deploy.task.tomcatTask.DeployStartServerTask.call start finish taskId=" + this.taskId);
        WinitTomcatInfo tomcatInfo = this.winitTomcatServer.getWinitTomcatInfo();
        logger.info("com.winit.deploy.task.tomcatTask.DeployStartServerTask.call 判断是否要清理redis .isCleanRedis=" + isCleanRedis);
        if (ConfigUtil.getValue("redis_clean_env_list").contains("," + tomcatInfo.getEnvName() + ",") && this.isCleanRedis) {
            RedisUtil.cleanProjectRedis(ProjectUtil.getTrunkProjectName(this.winitTomcatServer.getWinitTomcatInfo().getProjectName()), handler);
        }

        logger.info("com.winit.deploy.task.tomcatTask.DeployStartServerTask.call end taskId=" + this.taskId);
        return TaskStatus.STATUS_SUCCESS;
    }
}
